<?php

namespace App\Http\Controllers\Myorder;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Service\ServiceController;
use App\library\Pingpp\Error\Api;
use App\Models\AccountRecordModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use App\Http\Components\UserComponent;
use App\Http\Components\MessageComponent;
use App\Http\Components\AccountComponent;
use App\Models\ServiceModel;
use App\Models\LogOrderModel;
use App\Models\UserAccountModel;
use App\Models\UserSettingModel;
use App\Models\UserProfileModel;
use App\Models\DataConfigModel;
use App\library\UploadFile;


/**
 * 取消、拒绝订单
 */
class CancelOrderController extends ApiController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->cancel_order($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 取消、拒绝订单
     */
    public function cancel_order(Request $request){

        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $customAttr = [
            'order_id'=>'订单号',
        ];
        $this->validate($request, [
            'order_id'=>'required',
        ],[ ], $customAttr);
        $status = 6;
        $type = $request->input('type');    //type==report投诉处理
        $order_id = $request->input('order_id');
        $cancel_reason = $request->input('cancel_reason');

        $order = OrderModel::where("order_id",$order_id)
            ->where(function($query) use ($user_id){
                $query->where('order.user_id','=',$user_id)
                    ->orwhere('order.pay_user_id','=',$user_id);
            })->first();

        if($order){
            if($order->status == 2 && empty($cancel_reason)){
                return $this->json('0','请输入取消原因!');
            }

            $previous_status = $order->status;
            if($order->status != 1 && $order->status != 2 && $order->status != 7){
                return $this->json('0','订单状态有误!');
            }

            $order->status = $status;
            $order->previous_status = $previous_status;
            $order->uptime = date("Y-m-d H:i:s");
            $order->cancel_reason = $cancel_reason;
            $result = $order->saveOrFail();
            if($result){
                //调用退款申请
                if(!empty($order->ping_id)){
                    $refund_result = AccountComponent::refund($order->ping_id,round($order->price-$order->balance,2));
                    $refund_result = json_decode($refund_result,true);
                    if(!($refund_result && !empty($refund_result['id']) && ($refund_result['status'] = 'succeeded'))){
                        return $this->json('0','申请退款失败!');
                    }
                }
                $userAccount = UserAccountModel::where("user_id",$order->pay_user_id)->first();
                $userAccount->income = $userAccount->income+$order->price;
                $userAccount->balance = $userAccount->balance+$order->balance;
                $userAccount->saveOrFail();

                //记录金额日志
                $account_record = new AccountRecordModel();
                $account_record->save_records($order->pay_user_id,$order->order_id,+$order->price,8);

                //获取取消时间配置
                $config = new DataConfigModel();
                $limit_day = $config->get_value('cancel_forbid_time');
                $user_setting = UserSettingModel::where('user_id',$user_id)->first();

                //获取用户信息
                $user_profile = UserProfileModel::where('user_id',$user_id)->first()->toArray();

                //记录订单状态变更日志
                $log_order = new LogOrderModel();
                $log_order->save_log($user_id,$order_id,$previous_status,$status);

                //卖家未接单 拒绝订单
                if($previous_status == 1){
                    if( $user_id == $order->user_id){
//                        $user_setting->seller_refuse = $user_setting->seller_refuse+1;
//
//                        if($user_setting->seller_refuse>=3){    //拒绝订单3次 限制提供服务
//                            $user_setting->seller_limit_time = time()+($limit_day*86400);
//                            //发送服务限制推送
//                            MessageComponent::unite_push('seller_refuse_order_limit',array('user_id'=>$user_id,'order_id'=>$order_id),($limit_day*86400));
//                        }
//                        $user_setting->saveOrFail();
                        //发送拒绝订单推送
                        MessageComponent::unite_push('seller_refuse_order',array('user_id'=>$order->pay_user_id,'seller_name'=>$user_profile['nick_name'],'order_id'=>$order_id));
                    }else{
                        MessageComponent::unite_push('buyer_cancel_order',array('user_id'=>$order->user_id,'buyer_name'=>$user_profile['nick_name'],'order_id'=>$order_id));
                    }

                }elseif($previous_status == 2){ //已接单
                    if($order->pay_user_id == $user_id){  //买家取消订单
                        $user_setting->buyer_cancel = $user_setting->buyer_cancel+1;
                        if($user_setting->buyer_cancel>=3){
                            $user_setting->buyer_limit_time = time()+($limit_day*86400);
                            MessageComponent::unite_push('buyer_cancel_order_limit',array('user_id'=>$user_id),$limit_day*86400);
                        }
                        $user_setting->saveOrFail();
                        //已付款 买家取消订单
                        MessageComponent::unite_push('buyer_cancel_order',array('user_id'=>$order->user_id,'buyer_name'=>$user_profile['nick_name'],'order_id'=>$order_id));
                    }else{  //卖家取消订单
                        $user_setting->seller_cancel = $user_setting->seller_cancel+1;
                        if($user_setting->seller_cancel>=3){
                            $user_setting->seller_limit_time = time()+($limit_day*86400);
                            MessageComponent::unite_push('seller_cancel_order_limit',array('user_id'=>$user_id),$limit_day*86400);
                        }
                        $user_setting->saveOrFail();
                        //已付款 卖家取消订单
                        MessageComponent::unite_push('seller_cancel_order',array('user_id'=>$order->pay_user_id,'seller_name'=>$user_profile['nick_name'],'order_id'=>$order_id));
                    }
                }



                if($order->user_id == $user_id){
                    return $this->json('1','订单取消成功！');
                }else{
                    return $this->json('1','订单取消成功！');
                }

            }else{
                return $this->json('0','操作失败');
            }
        }else{
            return $this->json('0','该订单不存在!');
        }

    }
}